package com.example.yiwei.crm.view.activity.JYCoordingActivity;


import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;

import com.example.yiwei.crm.R;
import com.example.yiwei.crm.base.baseClass;
import com.example.yiwei.crm.util.NetWorkUtils;
import com.example.yiwei.crm.view.Class.GetLocationData;
import com.example.yiwei.crm.view.Class.NetWorkUtil;
import com.example.yiwei.crm.view.activity.coordinationActivity.*;
import com.google.zxing.datamatrix.decoder.Version;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

public class AddressChangeActivty extends AppCompatActivity {
    private EditText edit_address;
    private String address,jd,wd,message;
    private String map_type="";
    Marker marker;
    private String touchType;
    private String  address_result;
    private Double jd1,wd1;
    StringBuffer sb;
    String version;
    private String country,province,city,district,street,street_number,formatted_address,recommended_location_description;
    private LatLng currentPt;
    private String address1;
    int state;
    private ImageView img_back,img_commit;
    String result;
    public MapView mapView = null;
    public BaiduMap baiduMap = null;
    public LocationClient mLocationClient = null;
    private ImageView img_search;
    OverlayOptions option;
    BitmapDescriptor bitmap,bitmap1;
    LatLng point;
    Marker mMarkerD;
//    public BDLocationListener myListener = new BDLocationListener() {
//        public void onReceiveLocation(BDLocation location) {
//
//            // map view 销毁后不在处理新接收的位置
//            if (location == null || mapView == null)
//                return;
//            MyLocationData locData = new MyLocationData.Builder()
//                    .accuracy(location.getRadius())
//                    // 此处设置开发者获取到的方向信息，顺时针0-360
//                    .direction(100).latitude(location.getLatitude())
//                    .longitude(location.getLongitude()).build();
//            baiduMap.setMyLocationData(locData);    //设置定位数据
//            sb = new StringBuffer(256);
////            sb.append("time : ");
//            sb.append(location.getTime()+",");
//            sb.append(location.getLocationDescribe()+",");// 位置语义化信息
//            sb.append(location.getLatitude()+",");    //获取纬度信息
//            sb.append(location.getLongitude());    //获取经度信息
//            LatLng ll = new LatLng(location.getLatitude(),
//                    location.getLongitude());
//            MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(ll, 16);   //设置地图中心点以及缩放级别
//            baiduMap.animateMapStatus(u);
//        }
//    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(getApplication());
        setContentView(R.layout.activity_address_change_activty);
        edit_address= (EditText) findViewById(R.id.address);
        img_back= (ImageView) findViewById(R.id.address_img_back);
        img_commit= (ImageView) findViewById(R.id.address_img_commit);
        mapView = (MapView) this.findViewById(R.id.bmapView1); // 获取地图控件引用
        baiduMap = mapView.getMap();
        img_search= (ImageView) findViewById(R.id.address_search);
//        baiduMap.setMyLocationEnabled(true);
//        mLocationClient = new LocationClient(getApplicationContext()); // 实例化LocationClient类
//        mLocationClient.registerLocationListener(myListener); // 注册监听函数
//        initLocation(); //设置定位参数
//        mLocationClient.start(); // 开始定位
        //构建Marker图标

        bitmap = BitmapDescriptorFactory
                .fromResource(R.drawable.dingwei1);
        bitmap1 = BitmapDescriptorFactory
                .fromResource(R.drawable.address);
        if ("".equals(getIntent().getStringExtra("address"))&&getIntent().getStringExtra("address")==null){

        }else{
                edit_address.setText(getIntent().getStringExtra("address"));
            new Thread(new Runnable() {
                @Override
                public void run() {
                    String address =  getIntent().getStringExtra("address");
                    result= NetWorkUtil.getCount(baseClass.address_change_url,getIntent().getStringExtra("address"));
                    Log.d("aaa",getIntent().getStringExtra("address"));
                    Log.d("aaa",result);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                JSONObject object=new JSONObject(result);
                                state=object.getInt("status");
                                message=object.getString("message");
                                if (0==state){
                                    JSONArray array=object.getJSONArray("result");
                                    if (array.length()==0){
                                        Toast.makeText(AddressChangeActivty.this, "请检查地址是否输入错误！", Toast.LENGTH_SHORT).show();
                                    }else {
                                        for (int i = 0; i < array.length(); i++) {
                                            JSONObject json = array.getJSONObject(i);
                                            JSONObject json1 = json.getJSONObject("location");
                                            jd = json1.getString("lng");
                                            wd = json1.getString("lat");
                                            if (jd.equals("") && jd == null) {
                                                Toast.makeText(AddressChangeActivty.this, "请检查地址是否输入错误！", Toast.LENGTH_SHORT).show();
                                            } else {
                                                MyLocationData locData = new MyLocationData.Builder()
                                                        .latitude(Double.parseDouble(wd)).longitude(Double.parseDouble(jd)).build();
                                                LatLng ll = new LatLng(Double.parseDouble(wd),
                                                        Double.parseDouble(jd));
                                                //定义Maker坐标点
                                                point = new LatLng(Double.parseDouble(wd),
                                                        Double.parseDouble(jd));
//                                                option = new MarkerOptions()
//                                                        .position(point)
//                                                        .icon(bitmap);
//                                                OverlayOptions options = new MarkerOptions()
//                                                        .position(point)  //设置marker的位置
//                                                        .icon(bitmap1)  //设置marker图标
//                                                        .zIndex(9)  //设置marker所在层级
//                                                        .draggable(false);  //设置手势拖拽
//                                                baiduMap.addOverlay(option);
//                                                marker = (Marker) (baiduMap.addOverlay(options));
//                                                marker.setDraggable(false);
//                                                baiduMap.addOverlay(options);
                                                baiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
                                                    /**
                                                     * 单击地图
                                                     */
                                                    public void onMapClick(LatLng point) {
                                                        touchType = "单击地图";
                                                        map_type="click";
                                                        currentPt = point;
                                                        updateMapState();
                                                    }
                                                    /**
                                                     * 单击地图中的POI点
                                                     */
                                                    public boolean onMapPoiClick(MapPoi poi) {
                                                        touchType = "单击POI点";
                                                        currentPt = poi.getPosition();
//                                                        if (poi.getName()==null){
//                                                            Toast.makeText(AddressChangeActivty.this, "请点击建筑物，否则地址为空", Toast.LENGTH_SHORT).show();
//                                                        }else{
//                                                            address1=poi.getName();
//                                                        }
                                                        updateMapState();
                                                        return false;
                                                    }
                                                });
                                                option = new MarkerOptions()
                                                        .position(point)
                                                        .icon(bitmap);
                                                baiduMap.addOverlay(option);
                                                //在地图上添加Marker，并显示
                                                MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(ll, 16);   //设置地图中心点以及缩放级别
                                                baiduMap.animateMapStatus(u);
                                            }
                                        }
                                    }
                                }else{
                                    Toast.makeText(AddressChangeActivty.this, message+"", Toast.LENGTH_SHORT).show();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            }).start();
        }

        img_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                address=edit_address.getText().toString();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        result= NetWorkUtil.getCount(baseClass.address_change_url,edit_address.getText().toString());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    JSONObject object=new JSONObject(result);
                                    state=object.getInt("status");
                                    message=object.getString("message");
                                    if (0==state){
                                        JSONArray array=object.getJSONArray("result");
                                        if (array.length()==0){
                                            Toast.makeText(AddressChangeActivty.this, "请检查地址是否输入错误！", Toast.LENGTH_SHORT).show();
                                        }else {
                                            for (int i = 0; i < array.length(); i++) {
                                                JSONObject json = array.getJSONObject(i);
                                                JSONObject json1 = json.getJSONObject("location");
                                                jd = json1.getString("lng");
                                                wd = json1.getString("lat");
                                                if (jd.equals("") && jd == null) {
                                                    Toast.makeText(AddressChangeActivty.this, "请检查地址是否输入错误！", Toast.LENGTH_SHORT).show();
                                                } else {
                                                    MyLocationData locData = new MyLocationData.Builder()
                                                            .latitude(Double.parseDouble(wd)).longitude(Double.parseDouble(jd)).build();
                                                    LatLng ll = new LatLng(Double.parseDouble(wd),
                                                            Double.parseDouble(jd));
                                                    //定义Maker坐标点
                                                    point = new LatLng(Double.parseDouble(wd),
                                                            Double.parseDouble(jd));
                                                    option = new MarkerOptions()
                                                            .position(point)
                                                            .icon(bitmap);
                                                    baiduMap.addOverlay(option);
                                                    //在地图上添加Marker，并显示
                                                    MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(ll, 16);   //设置地图中心点以及缩放级别
                                                    baiduMap.animateMapStatus(u);
                                                }
                                            }
                                        }
                                    }else{
                                        Toast.makeText(AddressChangeActivty.this, message+"", Toast.LENGTH_SHORT).show();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });

                    }
                }).start();
            }
        });
        img_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (jd!=null&&!jd.equals("")){
                    GetLocationData.jd = jd;
                    GetLocationData.wd = wd;
                    GetLocationData.address=edit_address.getText().toString();
                    finish();
                }else{
                    Toast.makeText(AddressChangeActivty.this, "请点击搜索按钮或移动图标查看地址", Toast.LENGTH_SHORT).show();
                }
            }
        });
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    protected void onDestroy() {
        //退出时销毁定位
        // TODO Auto-generated method stub
        super.onDestroy();
        mapView.onDestroy();
        mapView = null;
    }
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        mapView.onResume();
    }

    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        mapView.onPause();
    }
private void updateMapState() {
    if (currentPt == null) {
        Toast.makeText(this, "网络不好请重新定位", Toast.LENGTH_SHORT).show();
    } else {
        jd1=currentPt.longitude;
        wd1=currentPt.latitude;
        jd=jd1.toString();
        wd=wd1.toString();
        new Thread(new Runnable() {
            @Override
            public void run() {
                 address_result=NetWorkUtil.getCount(baseClass.jwd_change_url+wd1+","+jd1,null);
                 Log.d("eeee",address_result);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            JSONObject object= new JSONObject(address_result);
                            state=object.getInt("status");
                            if (0==state) {
                                        JSONObject json = object.getJSONObject("address_component");
                                        country=json.getString("country");
                                        province=json.getString("province");
                                        city=json.getString("city");
                                        district=json.getString("district");
                                        street=json.getString("street");
                                if (json.has("street_number")){
                                    street_number=json.getString("street_number");
                                }
                                        formatted_address=object.getString("formatted_address");
                                        recommended_location_description=object.getString("recommended_location_description");
                                        address1=province+city+street;
                            }
                            edit_address.setText(formatted_address+"("+recommended_location_description+")");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }).start();
        MarkerOptions ooA = new MarkerOptions().position(currentPt).icon(bitmap);
        baiduMap.clear();
        baiduMap.addOverlay(ooA);
    }
}
}
